package cn.itrip.controller;

import cn.itrip.DTO.*;
import cn.itrip.entity.*;
import cn.itrip.service.*;
import cn.itrip.vo.R;
import cn.itrip.vo.biz.ItripAddCommentVO;
import cn.itrip.vo.biz.ItripSearchCommentVO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/comment")
public class CommentController {

    @Resource
    private ItripHotelService itripHotelService;
    @Resource
    private ItripCommentService itripCommentService;
    @Resource
    private ItripImageService itripImageService;
    @Resource
    private ItripLabelDicService itripLabelDicService;
    @Resource
    private TokenService tokenService;

    @ApiOperation(value = "查询酒店评分")
    @ApiResponses({ @ApiResponse(code = 200, message =  "OK", response = AvgCommentDTO.class) })
    @GetMapping("/gethotelscore/{hotelId}")
    public R getHotelScore(@PathVariable("hotelId") Long hotelId){
        ItripScoreCommentDTO avgAndTotalScore = itripCommentService.getAvgAndTotalScore(hotelId);
        return R.success("获取评分成功",avgAndTotalScore);
    }

    @ApiOperation(value = "查询评论数量")
    @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = CommentDTO.class) })
    @GetMapping("/getcount/{holetId}")
    public R getCount(@PathVariable("holetId") Long holetId){
        ItripHotel hotel = itripHotelService.getHotelByHotelId(holetId);
            Integer size = itripCommentService.getCommentByHotelId(hotel.getId()).size();
            Integer isok = itripCommentService.getCommentIsOkCount(hotel.getId());
            Integer improve = size-isok;
            CommentDTO commentDTO = new CommentDTO();
            commentDTO.setImprove(improve);
            commentDTO.setIsok(isok);
            commentDTO.setHavingimg(itripCommentService.getCommentHavingImgCount(hotel.getId()));
            commentDTO.setAllcomment(size);
        return R.success("获取酒店各类评论数成功",commentDTO);
    }

    @ApiOperation(value = "查询评论内容列表")
    @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = CommentListDTO.class) })
    @PostMapping("/getcommentlist")
    public R getCommentList(@RequestBody ItripSearchCommentVO itripSearchCommentVO) {
        if (itripSearchCommentVO.getIsOk() == -1) {
            itripSearchCommentVO.setIsOk(null);
        }
        if (itripSearchCommentVO.getIsHavingImg() == -1) {
            itripSearchCommentVO.setIsHavingImg(null);
        }
        try {
            cn.itrip.utils.Page<ItripListCommentDTO> page = itripCommentService.queryItripCommentPageByMap(itripSearchCommentVO);
            return R.success(null,page);
        } catch (Exception e) {
            e.printStackTrace();
            R r = new R();
            r.setMsg("获取评论列表错误");
            r.setErrorCode("100020");
            return r;
        }
    }

    @ApiOperation(value = "查询评论附带的图片")
    @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = CommentImageDTO.class) })
    @GetMapping("/getimg/{commentId}")
    public R getImg(@PathVariable("commentId") String commentId){
        List<ItripImage> list = itripImageService.getListByCommentId(commentId);
        List<CommentImageDTO> commentImageDTOS = new ArrayList<>();
        for (int i = 0;i<list.size();i++){
            CommentImageDTO commentImageDTO = new CommentImageDTO();
            commentImageDTO.setImgUrl(list.get(i).getImgUrl());
            commentImageDTO.setPosition(list.get(i).getPosition());
            commentImageDTOS.add(commentImageDTO);
        }
        return R.success("获取评论图片成功",commentImageDTOS);
    }

    @ApiOperation(value = "查询酒店详情（评论）")
    @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = HotelDescDTO.class) })
    @GetMapping("/gethoteldesc/{hotelId}")
    public R getHotelDesc(@PathVariable("hotelId") Long hotelId){
        ItripHotel itripHotel = itripHotelService.getHotelByHotelId(hotelId);
        HotelDescDTO hotelDescDTO = new HotelDescDTO();
        BeanUtils.copyProperties(itripHotel,hotelDescDTO);
        hotelDescDTO.setHotelId(hotelId);
        return R.success(null,hotelDescDTO);
    }

    @ApiOperation(value = "查询酒店详情（评论）")
    @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = ItripLabelDicDTO.class) })
    @GetMapping("/gettraveltype")
    public R getTravelType(){
        List<ItripLabelDic> list = itripLabelDicService.getTravelType();
        List<ItripLabelDicDTO> itripLabelDicDTOS = new ArrayList<>();
        for (int i = 0;i<list.size();i++){
            ItripLabelDicDTO itripLabelDicDTO = new ItripLabelDicDTO();
            itripLabelDicDTO.setId(list.get(i).getId());
            itripLabelDicDTO.setName(list.get(i).getName());
            itripLabelDicDTO.setDescription(list.get(i).getDescription());
            if(list.get(i).getPic()==null){
                itripLabelDicDTO.setPic("");
            }else {
                itripLabelDicDTO.setPic(list.get(i).getPic());
            }
            itripLabelDicDTOS.add(itripLabelDicDTO);
        }
        return R.success("获取旅游类型列表成功",itripLabelDicDTOS);
    }

    @ApiOperation(value = "新增评论")
    @ApiResponses({ @ApiResponse(code = 200, message = "OK") })
    @PostMapping(value = "/add",headers = {"token"})
    public R add(@RequestBody ItripAddCommentVO itripAddCommentVO, HttpServletRequest request){
        String tokenString = request.getHeader("token");
        ItripUser currentUser = tokenService.load(tokenString);
        if (null != currentUser && null != itripAddCommentVO) {
            //新增评论，订单id不能为空
            if (itripAddCommentVO.getOrderId() == null
                    || itripAddCommentVO.getOrderId() == 0) {
                R r = new R();
                r.setMsg("新增评论，订单ID不能为空");
                r.setErrorCode("100005");
                return r;
            }
            List<ItripImage> itripImages = null;
            ItripComment itripComment = new ItripComment();
            itripComment.setContent(itripAddCommentVO.getContent());
            itripComment.setHotelId(itripAddCommentVO.getHotelId());
            itripComment.setIsHavingImg(itripAddCommentVO.getIsHavingImg());
            itripComment.setPositionScore(itripAddCommentVO.getPositionScore());
            itripComment.setFacilitiesScore(itripAddCommentVO.getFacilitiesScore());
            itripComment.setHygieneScore(itripAddCommentVO.getHygieneScore());
            itripComment.setOrderId(itripAddCommentVO.getOrderId());
            itripComment.setServiceScore(itripAddCommentVO.getServiceScore());
            itripComment.setProductId(itripAddCommentVO.getProductId());
            itripComment.setProductType(itripAddCommentVO.getProductType());
            itripComment.setIsOk(itripAddCommentVO.getIsOk());
            itripComment.setTripMode(itripAddCommentVO.getTripMode());
            itripComment.setCreatedBy(currentUser.getId());
            itripComment.setCreationDate(new Date(System.currentTimeMillis()));
            itripComment.setUserId(currentUser.getId());
            try {
                if (itripAddCommentVO.getIsHavingImg() == 1) {
                    itripImages = new ArrayList<ItripImage>();
                    //loop input imgs array
                    int i = 1;
                    for (ItripImage itripImage : itripAddCommentVO.getItripImages()) {
                        itripImage.setPosition(i);
                        itripImage.setCreatedBy(currentUser.getId());
                        itripImage.setCreationDate(itripComment.getCreationDate());
                        itripImage.setType("2");
                        itripImages.add(itripImage);
                        i++;
                    }
                }
                itripCommentService.itriptxAddItripComment(itripComment, (null == itripImages ? new ArrayList<ItripImage>() : itripImages));
                return R.success("新增评论成功");
            } catch (Exception e) {
                e.printStackTrace();
                R r = new R();
                r.setMsg("新增评论失败");
                r.setErrorCode("100003");
                return r;
            }
        } else if (null != currentUser && null == itripAddCommentVO) {
            R r = new R();
            r.setMsg("不能提交空，请填写评论信息");
            r.setErrorCode("100004");
            return r;
        } else {
            R r = new R();
            r.setMsg("token失效，请重登录");
            r.setErrorCode("100000");
            return r;
        }
    }
}
